package com.epoch.platform.sys.generator.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.epoch.base.annotation.ControllerBind;
import com.epoch.base.base.BaseController;
import com.epoch.base.constant.Constant;
import com.epoch.platform.sys.generator.service.GeneratorService;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

@ControllerBind(controllerKey = "/sys/generator")
public class SysGeneratorController extends BaseController{
	
	public void index() {
		this.render("/sys/generator/sys_generator_tab.html");
	}
	
	public void listUI() {
		this.render("/sys/generator/sys_generator_list.html");
	}
	
	public void findListDbAjax() {
		Kv params = commonParams();
		Integer pageSize = getParaToInt("pageSize");
		SqlPara sqlPara = Db.getSqlPara("systemManage.findDbDataList", params);
        Integer pageNumber = getParaToInt("pageNumber", Integer.valueOf(Constant.INT1));
		Page<Record> list = Db.paginate(pageNumber,pageSize,sqlPara);
		renderJson(list);
	}
	
	public void code() throws IOException {
		String[] tableNames = getPara("ids").split(",");
		byte[] data = new GeneratorService().generatorCode(tableNames);
		HttpServletResponse response = getResponse();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"epoch_code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        renderNull();
        IOUtils.write(data, response.getOutputStream());
	}
	
	public void codeStart() throws IOException {
		String tableNames = getPara("name");
		byte[] data = new GeneratorService().generatorCodeStart(tableNames);
		HttpServletResponse response = getResponse();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"epoch_code.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        renderNull();
        IOUtils.write(data, response.getOutputStream());
	}
	
}
